<!--
 * @Description: 流程工具栏
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-07-09 14:06:11
 * @LastEditTime: 2022-09-23 11:29:57
-->
<template inherit-attrs="false">
	<div
		class="pok-tool-bar"
		:class="{
			'pok-done-task': taskTypeEnum.DoneTask === taskType && !isChangeLayout,
			'pok-tool-bar-layout': !isChangeLayout && taskType !== 'Drafts',
		}"
	>
		<DropCheckSkeleton
			v-if="
				taskLoading && taskTypeEnum.AgentTodo === taskType && !isChangeLayout
			"
			style="width: 236; height: 32"
		/>
		<template v-else>
			<div
				class="filter-title-box"
				v-if="!isChangeLayout && taskType !== 'Drafts'"
			>
				<div class="filter-title">
					{{ $t('pages.process.processfiltering', '流程筛选') }}
				</div>
				<div class="filter-btn">
					<a-button
						type="primary"
						size="small"
						@click="handleSearch"
						:disabled="
							!isHas
								? !checkDataRef?.length
								: !checkDataRef?.length || !checkAgentDataRef?.length
						"
						>{{ $t('pages.process.filter', '筛选') }}
					</a-button>
					<a-button size="small" @click="handleReset">{{
						$t('pages.process.reset', '重置')
					}}</a-button>
				</div>
			</div>
		</template>
		<div
			class="pok-tool-bar-box"
			:class="{
				'pok-task-tab-flex': !isChangeLayout,
				'pok-task-tab-height': !isChangeLayout && taskType === 'DoneTask',
			}"
		>
			<section
				v-if="taskTypeEnum.DoneTask === taskType"
				style="height: 32px"
				:class="{ 'done-tsak-tab': !isChangeLayout }"
			>
				<slot name="bidButton"></slot>
			</section>
			<section class="left-block">
				<div v-if="taskTypeEnum.Drafts === taskType && isChangeLayout">
					<a-button
						type="primary"
						:disabled="!selectedRows.length"
						@click="handleDeleteDrafts"
					>
						{{ iTrans('pages.process.deleteSelect', '删除选中项') }}
					</a-button>
				</div>
				<template v-else-if="selectedRows.length && isChangeLayout">
					<div class="selected">
						<a-avatar
							:size="28"
							class="avatar-clear"
							@click="handleClearSelect"
						>
							<i class="low-code iconcuo clear-icon"></i>
						</a-avatar>
						{{
							iTrans(
								'pages.process.select.selected',
								`已选表单 ${selectedRows.length}`,
								{ count: selectedRows.length }
							)
						}}
					</div>
				</template>
				<section
					v-show="
						(isChangeLayout &&
							!selectedRows.length &&
							taskTypeEnum.Drafts !== taskType) ||
						(!isChangeLayout && taskTypeEnum.Drafts !== taskType)
					"
					style="display: flex"
					:class="{ 'left-block-layout': !isChangeLayout }"
				>
					<a-select
						v-model:value="checked"
						@change="changeChecked"
						class="filter-entrust-todo"
						v-if="taskTypeEnum.TodoTask == taskType && isChangeLayout"
					>
						<a-select-option :value="false">{{
							$t('delegate.unfiller', '显示委托待办')
						}}</a-select-option>
						<a-select-option :value="true">{{
							$t('delegate.filler', '过滤委托待办')
						}}</a-select-option>
						<template #suffixIcon
							><i class="low-code iconpackup arrow-icon"></i
						></template>
					</a-select>
					<DropCheckSkeleton
						v-if="taskLoading"
						style="width: 236; height: 32"
					/>
					<!-- 流程类别选择 -->

					<drop-checkbox
						v-else
						:done-type="doneType"
						:check-options="checkOptions"
						:check-agent-options="checkAgentOptions"
						:check-data="checkDataRef"
						:check-total="checkTotalRef"
						:disabled="isRequesting"
						:isChangeLayout="isChangeLayout"
						:isAgentCheck="!isAgentCheck"
						:taskType="taskType"
						:filterChecked="checked"
						:resetCheckVal.sync="resetCheckVal"
						@getCheckData="getTypeCheckData"
						@changeChecked="changeChecked"
						class="task-type task-type-checkbox"
						:placeholder="iTrans('placeholder.select', '请选择')"
						:tag-render="
							!checkDataRef.length || checkDataRef.length >= checkOptions.length
								? iTrans(
										'pages.process.select.allProcesses',
										`${checkTotalRef.text}`
								  )
								: iTrans(
										'component.state.checked',
										`已选 ${checkDataRef.length} 项`,
										{ count: checkDataRef.length }
								  )
						"
						:class="{ 'task-type-box': isChangeLayout }"
						@on-blur="handleUpdateTypeKeys"
					/>
					<section
						v-show="!selectedRows.length && taskTypeEnum.AgentTodo === taskType"
						style="display: flex"
					>
						<DropCheckSkeleton
							v-if="taskLoading"
							style="width: 236; height: 32"
						/>
						<!-- 委托人选择 -->
						<drop-checkbox
							v-else
							class="task-type"
							:done-type="doneType"
							:check-options="checkAgentOptions"
							:check-data="checkAgentDataRef"
							:check-total="checkAgentTotalRef"
							:disabled="isRequesting"
							:isChangeLayout="isChangeLayout"
							:taskType="taskType"
							:isAgentCheck="isAgentCheck"
							:resetCheckVal.sync="resetCheckVal"
							:filterChecked="checked"
							@getCheckData="getAgentCheckData"
							@handleSearch="handleSearch"
							:placeholder="iTrans('placeholder.select', '请选择')"
							:tag-render="
								!checkAgentDataRef ||
								checkAgentDataRef.length >= checkAgentOptions.length
									? iTrans(
											'pages.process.select.allAgents',
											`${checkAgentTotalRef.text}`
									  )
									: iTrans(
											'component.state.checked',
											`已选 ${checkAgentDataRef.length} 项`,
											{
												count: checkAgentDataRef.length,
											}
									  )
							"
							@on-blur="handleUpdateAgent"
						/>
					</section>

					<DropCheckSkeleton
						v-if="taskSelect[taskType]?.length && taskLoading"
						style="width: 236; height: 32"
					/>

					<!-- 审批、知会等类型选择 -->
					<a-select
						v-else-if="
							taskSelect[taskType]?.length && isShowSelect && isChangeLayout
						"
						v-model:value="selectTypeRef"
						style="width: 200px; margin-right: 8px"
						:placeholder="iTrans('placeholder.select', '请选择')"
						dropdown-class-name="tool-select"
						:disabled="isRequesting"
						@change="handleChangeType"
					>
						<template #suffixIcon>
							<i class="low-code iconpackup" />
						</template>
						<!-- {{ taskTypeTodoTask }} -->
						<a-select-option
							v-for="item in taskOptions"
							:key="item?.value"
							:value="item?.value"
						>
							<div class="select-option">
								<span class="select-option-text">{{ item?.text }}</span>
								<span v-if="item.count" class="select-option-count">
									{{ item?.count }}
								</span>
							</div>
						</a-select-option>
					</a-select>
					<a-button
						v-if="
							taskType === 'TaskNotice' &&
							selectTypeRef === 'todo' &&
							selectCountRef >= 0 &&
							isChangeLayout
						"
						type="primary"
						style="margin-right: 20px"
						:disabled="selectCountRef === 0"
						@click="checkAllRead"
					>
						{{ iTrans('personalCenter.allReadBtn', '全部标记为已读') }}
					</a-button>
				</section>
			</section>
			<section class="right-block" v-if="isChangeLayout">
				<div v-show="!selectedRows.length || taskTypeEnum.Drafts === taskType">
					<input-search
						ref="inputSearch"
						:search-placeholder="searchPlaceholder"
						:task-type="taskType"
						style="width: 384px"
						:done-type="doneType"
						@search="onSearch"
					></input-search>
				</div>
				<div
					v-show="
						selectedRows.length &&
						taskTypeEnum.Drafts !== taskType &&
						isChangeLayout
					"
				>
					<a-space :size="12">
						<a-button type="primary" @click="handleAgree">{{
							iTrans('common.agree', '同意')
						}}</a-button>
					</a-space>
				</div>
			</section>
		</div>
	</div>
</template>

<script setup lang="ts">
import {
	ref,
	unref,
	watch,
	createVNode,
	computed,
	onMounted,
	reactive,
} from 'vue'
import type { Ref } from 'vue'
import { Modal } from 'ant-design-vue'
import { useStore } from 'vuex'
import { debounce } from 'lodash'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import { i18n } from '@/locales'
import DropCheckbox from '@/entry_desktop/components/DropCheckBox'
import DropSelect from '@/entry_desktop/components/DropSelect/index.vue'
import InputSearch from '@/entry_desktop/components/InputSearch/index.vue'
import { taskTypeEnum, doneTaskEnum } from '@/constant/enums/processCenter'
import { taskSelect } from './constant/task'
import { DropCheckSkeleton } from './skeleton'
import './index.vue'
const { $t: iTrans, locale } = i18n

const props = defineProps<{
	selectedRows: Recordable<any>[]
	taskType: keyof typeof taskTypeEnum
	cacheData: Recordable<any>
	taskLoading: boolean
	agreePromise?: (resolve: any, reject: any) => void
	batchPromise?: () => void
	deletePromise?: (
		draftIds: string[],
		resolve?: any,
		reject?: any
	) => Promise<void>
	checkOptions: []
	checkData: []
	checkTotal: Recordable<any>
	checkAgentOptions: []
	checkAgentData: []
	checkAgentTotal: Recordable<any>
	applyCount: Recordable<any>
	doneType: string
	isRequesting: boolean
	isChangeLayout: boolean
	selectType: string
	taskCountRef: Recordable<any>
}>()
const emit = defineEmits([
	'onClearSelect',
	'onSearch',
	'getSelectTypeList',
	'getResetVal',
])
const store = useStore()
const taskCount = computed(() => store.state.taskCount)
const subjectRef = ref('')
const inputSearch = ref()
const checked = ref(
	localStorage.getItem('authority')
		? JSON.parse(localStorage.getItem('authority') || '')
		: false
)
// const typeKeysRef = ref('')
const agentRef = ref('')
const extraParamRef: Ref<Recordable<any>> = ref({})
const selectTypeRef = ref('approve')
const selectCountRef = ref(0)
const searchPlaceholder = computed(() => {
	let placeholder = ''
	if (props.taskType === taskTypeEnum.Drafts) {
		placeholder = iTrans('pages.process.search.draftsPlaceholder', '流程名称')
	} else if (props.taskType === taskTypeEnum.Apply) {
		placeholder = iTrans(
			'pages.process.search.applyPlaceholder',
			'流程名称、任务主题'
		)
	} else if (props.taskType === taskTypeEnum.ExpactTask) {
		placeholder = iTrans(
			'pages.process.search.expactTaskPlaceholder',
			'流程名称、任务主题、申请人、当前负责人'
		)
	} else {
		placeholder = iTrans(
			'pages.process.search.placeholder',
			'流程名称、任务主题、申请人'
		)
	}
	return placeholder
})
// 全部流程select
const checkDataRef: any = ref([])
const checkTotalRef: Ref<Recordable<any>> = ref({})

// 全部委托人
const checkAgentDataRef: any = ref([])
const checkAgentTotalRef: Ref<Recordable<any>> = ref({})

// 区分 全部委托 和 全部流程 组件
const isAgentCheck = ref(true)

// 申请人option
const taskOptions: any = ref([])
const isShowSelect: any = ref(false)
const isHas = computed(() => props.checkAgentOptions.length)

watch(
	() => props.selectType,
	() => {
		selectTypeRef.value = props.selectType
	}
)

watch(
	() => props.doneType,
	() => {
		selectTypeRef.value = ''
	}
)

watch(
	() => props.applyCount,
	(value, old) => {
		isShowSelect.value = false
		setTimeout(() => {
			if (props.taskType === 'DoneTask') {
				taskOptions.value = taskSelect[props.taskType]?.map(item => {
					item.count = 0
					for (let key in props.applyCount) {
						if (item.value === props.applyCount[key].command_type) {
							item.count = props.applyCount[key].count
						}
					}
					return item
				})
				// .filter(item => item.count > 0 || item.value === '')
			} else {
				taskOptions.value = taskSelect[props.taskType]?.map(item => {
					if (
						['approve', 'all', 'complete', 'termination'].includes(
							item.value
						) ||
						item.value === 'todo'
					) {
						if (item.value === 'approve') {
							item.count = props.applyCount.approve_count
						} else if (item.value === 'all') {
							item.count = props.applyCount.sum_count
						} else if (item.value === 'complete') {
							item.count = props.applyCount.complete_count
						} else if (item.value === 'termination') {
							item.count = props.applyCount.termination_count
						} else {
							item.count = props.applyCount.un_read_count
							selectCountRef.value = props.applyCount.un_read_count
						}
					}
					return item
				})
			}
			isShowSelect.value = true
		})
	}
)

watch(
	() => props.taskType,
	(value, prevValue) => {
		if (value !== prevValue) {
			// 右上方input重新赋值
			subjectRef.value = props.cacheData?.[value]?.subject ?? ''

			// 左上方全部流程select重新赋值
			checkDataRef.value = props.checkData
			checkTotalRef.value = props.checkTotal

			// 全部委托人select重新赋值
			checkAgentDataRef.value = props.checkAgentData
			checkAgentTotalRef.value = props.checkAgentTotal
			// 审批人
			if (props.taskType === taskTypeEnum.Apply) {
				selectTypeRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[1]?.value
			}
			// 我的已办
			if (props.taskType === taskTypeEnum.DoneTask) {
				selectTypeRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[0]?.value
			}
			// 我的知会
			if (taskTypeEnum.TaskNotice === unref(props.taskType)) {
				selectTypeRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[0]?.value
				selectCountRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[0]?.count
			}
		}
	},
	{
		immediate: true,
	}
)
// 全部流程select option数据监听
watch(
	() => props.checkOptions,
	(value, prevValue) => {
		checkDataRef.value = checkDataRef.value.filter((item: any) => {
			return value.find((x: any) => x.value == item)
		})
	}
)
watch(
	() => props.checkAgentOptions,
	(value, prevValue) => {
		if (!checkAgentDataRef.value.length) {
			// 无一选中情况
			checkAgentDataRef.value = value.map((item: any) => item.value)
		}
	}
)
watch(
	() => props.checkData,
	(val: any) => {
		if (!val.length) {
			// 无一选中情况
			checkDataRef.value = props.checkOptions.map((item: any) => item.value)
		} else {
			checkDataRef.value = val
		}
	}
)

const handleClearSelect = () => {
	emit('onClearSelect')
}

const handleUpdateList = debounce((type = '') => {
	let selectTypeLocalVal = ''
	if (taskTypeEnum.Apply === unref(props.taskType)) {
		selectTypeLocalVal = selectTypeRef.value
	}
	let noticeType = ''
	if (taskTypeEnum.TaskNotice === unref(props.taskType)) {
		noticeType = selectTypeRef.value
	}
	let commandType = ''
	if (taskTypeEnum.DoneTask === unref(props.taskType)) {
		commandType = selectTypeRef.value
	}
	let typeKeyList = checkDataRef?.value?.join(',') || ''
	if (props.checkOptions.length === checkDataRef?.value?.length) {
		typeKeyList = ''
	}
	emit(
		'onSearch',
		Object.assign(
			{
				subject: subjectRef,
				type_key_list: typeKeyList,
				agent_id: checkAgentDataRef?.value?.join(','),
				total_count_data: checkTotalRef,
				agent_id_total: checkAgentTotalRef,
			},
			{
				status: selectTypeLocalVal,
				type: noticeType,
				command_type: commandType,
			}
		),
		type
	)
})

// 搜索
const onSearch = debounce((value: string) => {
	subjectRef.value = value
	handleUpdateList()
}, 800)

const handleUpdateTypeKeys = (value: any) => {
	const list: any = props.checkOptions?.map((item: any) => item.value)
	if (!value.length) {
		checkDataRef.value = list
		checkTotalRef.value = props.checkTotal
	} else {
		// 如果取消选中，则重新赋值为默认全选
		checkDataRef.value = value
	}

	if (taskTypeEnum.AgentTodo === unref(props.taskType)) {
		checkAgentDataRef.value = []
	}
	if (taskTypeEnum.DoneTask === unref(props.taskType)) {
		selectTypeRef.value = ''
	}
	handleUpdateList('allOption')
}
const handleUpdateAgent = (value: string) => {
	const list: any = props.checkAgentOptions?.map((item: any) => item.value)
	if (!value.length) {
		//如果取消选中，则重新赋值为默认全选
		checkAgentDataRef.value = list
		checkAgentTotalRef.value = props.checkAgentTotal
	} else {
		checkAgentDataRef.value = value
	}
	handleUpdateList()
}

const handleChangeType = () => {
	extraParamRef.value = {}
	// 后续优化
	if (taskTypeEnum.Apply === unref(props.taskType)) {
		unref(extraParamRef)['status'] = unref(selectTypeRef)
	}
	if (taskTypeEnum.TaskNotice === unref(props.taskType)) {
		unref(extraParamRef)['type'] = unref(selectTypeRef)
	}
	if (taskTypeEnum.DoneTask === unref(props.taskType)) {
		unref(extraParamRef)['type'] = unref(selectTypeRef)
	}
	handleUpdateList()
}

const changeChecked = (value: any) => {
	checked.value = typeof value === 'boolean' ? value : value?.target?.checked
	localStorage.setItem('authority', JSON.stringify(checked.value))
	handleUpdateList()
}

const handleAgree = () => {
	Modal.confirm({
		title: iTrans(
			'pages.process.agreeTip',
			`是否同意 ${props.selectedRows.length} 条审批任务？`,
			{ count: props.selectedRows.length }
		),
		okText: iTrans('personalCenter.confirm', '确认'),
		cancelText: iTrans('personalCenter.cancel', '取消'),
		icon: createVNode(QuestionCircleOutlined),
		onOk() {
			return new Promise((resolve, reject) => {
				if (props.agreePromise) {
					props.agreePromise(resolve, reject)
				} else {
					reject()
				}
			})
		},
	})
}

const handleDeleteDrafts = () => {
	Modal.confirm({
		title: iTrans('pages.process.batchDeleteTip', `确定删除已选中的表单？`),
		icon: createVNode(QuestionCircleOutlined),
		okText: iTrans('common.confirm', '确认'),
		cancelText: iTrans('common.cancel', '取消'),
		onOk() {
			return new Promise((resolve, reject) => {
				if (props.deletePromise) {
					props.deletePromise(
						props.selectedRows.map(item => item.draft_id),
						resolve,
						reject
					)
				} else {
					reject()
				}
			})
		},
	})
}

const clearParentInput = (value: any) => {
	unref(unref(inputSearch)?.clearInput())
}

// 全部标记为已读 button
const checkAllRead = () => {
	Modal.confirm({
		title: iTrans(
			'pages.process.allReadTip',
			`确认将 ${selectCountRef.value} 条知会标记为已读？`,
			{ count: selectCountRef.value }
		),
		icon: createVNode(QuestionCircleOutlined),
		centered: true,
		okText: iTrans('common.confirm', '确认'),
		cancelText: iTrans('common.cancel', '取消'),
		onOk() {
			if (props.batchPromise) {
				props.batchPromise()
			}
		},
	})
}

//左右布局 获取委托人选中数据
const getAgentCheckData = (val: any) => {
	checkAgentDataRef.value = val
}
//左右布局 获取流程类别选中数据
const getTypeCheckData = (val: any) => {
	checkDataRef.value = val
}
watch([() => checkDataRef.value, () => selectTypeRef.value], (val: any) => {
	emit('getSelectTypeList', val)
})
// 切换为左右布局 筛选
const handleSearch = debounce(() => {
	handleUpdateList()
	if (taskTypeEnum.AgentTodo === unref(props.taskType)) {
		handleUpdateTypeKeys(checkDataRef.value)
	}
})
// 重置
let resetCheckVal = reactive([''])
const handleReset = () => {
	resetCheckVal[0] = 'reset'
	if (taskTypeEnum.AgentTodo === unref(props.taskType)) {
		checkAgentDataRef.value = props.checkAgentOptions?.map(
			(item: any) => item.value
		)
	}
	if (taskTypeEnum.DoneTask === unref(props.taskType)) {
		selectTypeRef.value = ''
	}
	checkDataRef.value = props.checkOptions?.map((item: any) => item.value)
	changeChecked(false)
	emit('getResetVal', Date.now())
	handleUpdateList('allOption')
}
defineExpose({
	subjectRef,
	selectTypeRef,
	checkDataRef,
	checkTotalRef,
	clearParentInput,
})
</script>
<style lang="less" scoped>
.left-block-layout {
	display: flex;
	flex-direction: column;
	height: 100%;
	width: 100%;
}
.task-type-checkbox {
	height: 100%;
}
.task-type-box {
	margin-right: 8px;
}
.pok-done-task {
	flex-direction: column;
}
.pok-tool-bar-layout {
	min-width: 281px;
	max-width: 340px;
	margin-right: 16px;
	border-right: 1px solid #e8eaed;
}
.done-tsak-tab {
	margin-bottom: 22px;
}
.pok-task-tab-flex {
	display: flex;
	flex-direction: column;
	height: calc(100% - 40px);
}
.pok-task-tab-height {
	height: calc(100% - 75px);
}
.pok-tool-bar {
	.filter-title-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
		width: 95%;
		.filter-title {
			font-size: 14px;
			font-weight: 500;
			color: #1f2329;
		}
		.filter-btn {
			.ant-btn {
				font-weight: 500;
				font-size: 12px;
				color: rgba(0, 0, 0, 0.85);
				&:last-child:hover {
					color: var(--bl-brand-c);
				}
			}
			.ant-btn-primary {
				color: #fff;
				margin-right: 8px;
			}
		}
	}
}
.filter-entrust-todo {
	width: 220px;
	margin-right: 8px;
}
</style>
